/*
 * Copyright © 2010 SenseForce.com.
 * The Software shall be used for Good, not Evil.
 */

package com.senseforce.midlets;

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

/**
 * @author jcccn
 * @site http://www.senseforce.com/
 */
public class StartHTTP extends MIDlet implements CommandListener {
    private Display display;
    private TextBox tbMain;
    private Alert alStatus;
    private Form mainForm;
    private Command exitC;
    private Command viewC;
    private Command backC;
    private static final int ALERT_DSIPLAY_TIME = 3000;
    Image img = null;

    public StartHTTP() {
        super();
    }

    public void startApp() {
        display = Display.getDisplay(this);
        mainForm = new Form("Test Wireless");
        tbMain = new TextBox("Input Image URL", "http://img01.taobaocdn.com/tps/i1/T1zsBMXatNXXXXXXXX-170-65.png", 75, 0);
        exitC = new Command("Exit", Command.EXIT, 1);
        viewC = new Command("Download", Command.SCREEN, 2);
        backC = new Command("Back", Command.BACK, 1);
        tbMain.addCommand(exitC);
        tbMain.addCommand(viewC);
        tbMain.setCommandListener(this);
        mainForm.addCommand(backC);
        mainForm.setCommandListener(this);
        display.setCurrent(tbMain);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable d) {
        if (c == exitC) {
            destroyApp(true);
            notifyDestroyed();
        }
        else if (c == viewC) {
            showAlert("Downloading", false, tbMain);
            Download dl = new Download(tbMain.getString(), this);
            dl.start();
        }
        else if (c == backC) {
            display.setCurrent(tbMain);
        }
    }

    public void showAlert(String msg, boolean modal, Displayable d) {
        alStatus = new Alert("Status", msg, null, AlertType.INFO);
        if (modal) {
            alStatus.setTimeout(Alert.FOREVER);
        }
        else {
            alStatus.setTimeout(ALERT_DSIPLAY_TIME);
        }
        display.setCurrent(alStatus, d);
    }

    public void showImage(boolean flag) {
        if (flag) {
            ImageItem ii = new ImageItem(null, img, ImageItem.LAYOUT_DEFAULT, null);
            if (mainForm.size()!=0) {
//                System.out.println("set img");
                mainForm.set(0, ii);
            }
            else {
//                System.out.println("append img");
                mainForm.append(ii);
            }
//            System.out.println("Downloading succeeded!");
            alStatus = null;
            System.gc();
            display.setCurrent(mainForm);
            showAlert("Downloading succeeded!", true, mainForm);
        }
        else {
//            System.out.println("Downloading failed!");
            showAlert("Downloading failed!", true, tbMain);
        }
    }
}

class Download implements Runnable {
    private String url;
	private StartHTTP midlet;
	private boolean downloadingSuccess = false;
    public Download(String url, StartHTTP midlet) {
        this.url = url;
	this.midlet = midlet;
    }

    public void run() {
        try {
            getImage(url);
	} catch (Exception e) {
            System.err.println("Msg:" + e.toString());
	}
    }

    public void start() {
	Thread thread = new Thread(this);
	try {
            thread.start();
	} catch (Exception e) {

	}
    }
    
    private void getImage(String url) throws IOException {
		ContentConnection connection = (ContentConnection)Connector.open(url);
		DataInputStream dis = connection.openDataInputStream();
		ByteArrayOutputStream baos = null;
		Image img = null;
		try {
                    byte[] imageData;
			int length = (int)connection.getLength();
//                        System.out.println("length:"+length);
			if (length != -1) {
				imageData = new byte[length];
				dis.readFully(imageData);
			}
			else {
                            baos = new ByteArrayOutputStream();
				int ch;
				while ((ch = dis.read()) != -1) {
                                    baos.write(ch);
				}
				imageData = baos.toByteArray();
			}
			img = Image.createImage(imageData, 0, imageData.length);
		} finally {
                    if (connection != null) {
                        connection.close();
                    }
                    if (dis != null) {
                        dis.close();
                    }
                    if (baos != null) {
                        baos.close();
                    }
                    if (img == null) {
//                        System.out.println("img null");
                        downloadingSuccess = false;
                        midlet.showImage(false);
                    }
                    else {
//                        System.out.println("img not null");
                        downloadingSuccess = true;
                        midlet.img = img;
                        midlet.showImage(true);
                    }
                }
	}
}
